#include <windows.h>
#include <commctrl.h>
#include <string>
#include <vector>
#include <algorithm>
#include "MainWindow.hpp"
#include "RankingListWindow.hpp"
#include "YunUtility.hpp"
#include <nlohmann/json.hpp>

// 实现UTF-8字符串转宽字符串函数
std::wstring utf8_to_wstring(const std::string& str) {
    if (str.empty()) {
        return std::wstring();
    }
    
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
    std::wstring wstr(size_needed, 0);
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], size_needed);
    
    return wstr;
}

// 定义用户数据结构用于排序
typedef struct {
    std::wstring username;
    double averageDuration;
    double averageOperations;
    std::string cardCount;
} UserData;

// 刷新排行榜数据函数
void RefreshRankingList(HWND hListView, const std::string& currentCardCount) {
    // 清空ListView
    ListView_DeleteAllItems(hListView);
    
    // 收集当前卡牌数量下的所有用户数据
    std::vector<UserData> cardUsers;
    
    // 检查GameData中是否存在当前卡牌数量的数据
    if (GameData.contains(currentCardCount) && GameData[currentCardCount].is_object()) {
        // 遍历该卡牌数量下的所有用户
        for (auto& userIt : GameData[currentCardCount].items()) {
            std::string usernameStr = userIt.key();
            
            // 确保用户数据是对象类型
            if (!userIt.value().is_object()) {
                continue;
            }
            
            // 获取用户数据
            UserData user;
            user.username = utf8_to_wstring(usernameStr);
            user.averageDuration = userIt.value().value("AverageDuration", 0.0);
            user.averageOperations = userIt.value().value("AverageOperationsCount", 0.0);
            user.cardCount = currentCardCount;
            
            cardUsers.push_back(user);
        }
    }
    
    // 按照平均用时（升序）和平均操作次数（升序）排序
    std::sort(cardUsers.begin(), cardUsers.end(), [](const UserData& a, const UserData& b) {
        // 首先按平均用时排序
        if (a.averageDuration != b.averageDuration) {
            return a.averageDuration < b.averageDuration;
        }
        // 如果用时相同，则按操作次数排序
        return a.averageOperations < b.averageOperations;
    });
    
    // 添加排序后的用户数据到ListView
    for (size_t i = 0; i < cardUsers.size(); i++) {
        LVITEM lvi;
        lvi.mask = LVIF_TEXT;
        lvi.iItem = static_cast<int>(i);
        lvi.iSubItem = 0;
        
        // 排名
        std::wstring rankStr = std::to_wstring(i + 1);
        lvi.pszText = (LPWSTR)rankStr.c_str();
        int rowIndex = ListView_InsertItem(hListView, &lvi);
        
        // 用户名
        ListView_SetItemText(hListView, rowIndex, 1, (LPWSTR)cardUsers[i].username.c_str());
        
        // 平均用时
        std::wstring durationStr = std::to_wstring(cardUsers[i].averageDuration);
        // 移除末尾多余的0
        durationStr.erase(durationStr.find_last_not_of('0') + 1, std::string::npos);
        if (durationStr.back() == '.') {
            durationStr.pop_back();
        }
        ListView_SetItemText(hListView, rowIndex, 2, (LPWSTR)durationStr.c_str());
        
        // 平均操作次数
        std::wstring opsStr = std::to_wstring(cardUsers[i].averageOperations);
        // 移除末尾多余的0
        opsStr.erase(opsStr.find_last_not_of('0') + 1, std::string::npos);
        if (opsStr.back() == '.') {
            opsStr.pop_back();
        }
        ListView_SetItemText(hListView, rowIndex, 3, (LPWSTR)opsStr.c_str());
    }
    
    // 如果没有用户数据，显示提示信息
    if (cardUsers.empty()) {
        LVITEM lvi;
        lvi.mask = LVIF_TEXT;
        lvi.iItem = 0;
        lvi.iSubItem = 0;
        lvi.pszText = (LPWSTR)L"-";
        int rowIndex = ListView_InsertItem(hListView, &lvi);
        
        ListView_SetItemText(hListView, rowIndex, 1, (LPWSTR)L"暂无数据");
        ListView_SetItemText(hListView, rowIndex, 2, (LPWSTR)L"-");
        ListView_SetItemText(hListView, rowIndex, 3, (LPWSTR)L"-");
    }
}

// 定义工具栏按钮ID
#define ID_TOOLBAR_CARD_3  2000
#define ID_TOOLBAR_CARD_4  2001
#define ID_TOOLBAR_CARD_5  2002
#define ID_TOOLBAR_CARD_6  2003
#define ID_TOOLBAR_CARD_7  2004
#define ID_TOOLBAR_CARD_8  2005
#define ID_TOOLBAR_CARD_9  2006
#define ID_TOOLBAR_CARD_10 2007

// 排行榜窗口过程函数
LRESULT CALLBACK RankingListWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    static HWND hListView;
    static HWND hToolbar;
    static std::string currentCardCount = "3"; // 默认显示3张卡牌的排行榜
    
    switch (uMsg) {
    case WM_CREATE: {
        // 设置图标
        // 直接使用YunUtility中的LoadAppIcon函数加载图标
        LoadAppIcon(hWnd);
        
        // 初始化Common Controls库（用于ListView和Toolbar控件）
        INITCOMMONCONTROLSEX icex;
        icex.dwSize = sizeof(INITCOMMONCONTROLSEX);
        icex.dwICC = ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES;
        InitCommonControlsEx(&icex);

        // 创建工具栏
        hToolbar = CreateWindowEx(
            0,
            TOOLBARCLASSNAME,
            NULL,
            WS_CHILD | WS_VISIBLE | TBSTYLE_FLAT | CCS_ADJUSTABLE,
            0, 0, 0, 0,
            hWnd,
            NULL, // 工具栏不需要特定的菜单ID
            (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
            NULL);
        
        // 设置工具栏按钮大小
        SendMessage(hToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
        SendMessage(hToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(60, 25));
        
        // 按钮文本数组
        wchar_t buttonTexts[8][20] = {
            L"卡牌3", L"卡牌4", L"卡牌5", L"卡牌6",
            L"卡牌7", L"卡牌8", L"卡牌9", L"卡牌10"
        };
        
        // 按钮ID数组
        UINT buttonIds[8] = {
            ID_TOOLBAR_CARD_3, ID_TOOLBAR_CARD_4, ID_TOOLBAR_CARD_5, ID_TOOLBAR_CARD_6,
            ID_TOOLBAR_CARD_7, ID_TOOLBAR_CARD_8, ID_TOOLBAR_CARD_9, ID_TOOLBAR_CARD_10
        };
        
        // 向工具栏添加字符串
        for (int i = 0; i < 8; i++) {
            SendMessageW(hToolbar, TB_ADDSTRINGW, (WPARAM)0, (LPARAM)buttonTexts[i]);
        }
        
        // 创建工具栏按钮
        TBBUTTON tbb[8];
        ZeroMemory(tbb, sizeof(tbb));
        
        // 设置按钮属性
        for (int i = 0; i < 8; i++) {
            tbb[i].iBitmap = I_IMAGENONE;  // 无图标
            tbb[i].idCommand = buttonIds[i];
            tbb[i].fsState = TBSTATE_ENABLED;
            tbb[i].fsStyle = TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE;
            tbb[i].iString = i; // 使用字符串表中的索引
        }
        
        // 添加按钮到工具栏
        SendMessage(hToolbar, TB_ADDBUTTONS, 8, (LPARAM)tbb);
        
        // 调整工具栏大小
        SendMessage(hToolbar, TB_AUTOSIZE, 0, 0);
        
        // 获取工具栏高度
        RECT toolbarRect;
        GetClientRect(hToolbar, &toolbarRect);
        int toolbarHeight = toolbarRect.bottom - toolbarRect.top;
        
        // 确保工具栏高度至少为30像素
        if (toolbarHeight < 30) {
            toolbarHeight = 30;
        }
        
        // 标记默认选中的按钮
        SendMessage(hToolbar, TB_CHECKBUTTON, ID_TOOLBAR_CARD_3, TRUE);
        
        // 创建ListView控件，位置在工具栏下方
        hListView = CreateWindowEx(
            WS_EX_CLIENTEDGE,
            WC_LISTVIEW,
            L"",
            WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_SINGLESEL | WS_VSCROLL,
            10, toolbarHeight + 10, 780, 550, // 使用固定大小，稍后可以调整
            hWnd,
            NULL,
            (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE),
            NULL);
        
        // 设置ListView扩展样式
        ListView_SetExtendedListViewStyle(hListView, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
        
        // 添加列
        LVCOLUMN lvc;
        lvc.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM | LVCF_FMT;
        lvc.fmt = LVCFMT_LEFT;
        
        // 使用临时变量避免字符串字面量转换错误
        wchar_t col1[] = L"排名";
        lvc.cx = 50;
        lvc.pszText = col1;
        ListView_InsertColumn(hListView, 0, &lvc);
        
        wchar_t col2[] = L"用户名";
        lvc.cx = 200;
        lvc.pszText = col2;
        ListView_InsertColumn(hListView, 1, &lvc);
        
        wchar_t col3[] = L"平均用时";
        lvc.cx = 100;
        lvc.pszText = col3;
        ListView_InsertColumn(hListView, 2, &lvc);
        
        wchar_t col4[] = L"平均操作次数";
        lvc.cx = 100;
        lvc.pszText = col4;
        ListView_InsertColumn(hListView, 3, &lvc);
        
        // 初始化显示排行榜数据
        RefreshRankingList(hListView, currentCardCount);
        return 0;
    }

    case WM_COMMAND: {
        WORD wNotifyCode = HIWORD(wParam);
        WORD wID = LOWORD(wParam);
        
        // 处理工具栏按钮点击
        if (wNotifyCode == 0) {
            // 检查是否是工具栏按钮ID
            if (wID >= ID_TOOLBAR_CARD_3 && wID <= ID_TOOLBAR_CARD_10) {
                // 取消所有按钮的选中状态
                for (int i = ID_TOOLBAR_CARD_3; i <= ID_TOOLBAR_CARD_10; i++) {
                    SendMessage(hToolbar, TB_CHECKBUTTON, i, FALSE);
                }
                
                // 设置当前按钮为选中状态
                SendMessage(hToolbar, TB_CHECKBUTTON, wID, TRUE);
                
                // 更新当前卡牌数量（按钮ID减去基础ID再加3）
                int cardNum = (wID - ID_TOOLBAR_CARD_3) + 3;
                currentCardCount = std::to_string(cardNum);
                
                // 刷新排行榜数据，使用外部函数
                RefreshRankingList(hListView, currentCardCount);
                
                return 0;
            }
        }
        
        return 0;
    }
    
    case WM_CLOSE:
        ShowWindow(::hWnd, SW_SHOW);
        DestroyWindow(hWnd);
        RankingListWindow = NULL;
        return 0;
        
    case WM_SIZE:
    {
        RECT clientRect;
        GetClientRect(hWnd, &clientRect);
        
        // 获取工具栏高度
        RECT toolbarRect;
        GetClientRect(hToolbar, &toolbarRect);
        int toolbarHeight = toolbarRect.bottom - toolbarRect.top;
        
        // 确保工具栏高度至少为30像素
        if (toolbarHeight < 30) {
            toolbarHeight = 30;
        }
        
        // 调整工具栏大小
        MoveWindow(hToolbar, 0, 0, clientRect.right, toolbarHeight, TRUE);
        SendMessage(hToolbar, TB_AUTOSIZE, 0, 0);
        
        // 调整ListView大小和位置，确保它在工具栏下方
        MoveWindow(hListView, 10, toolbarHeight + 10, 
                  clientRect.right - 20, clientRect.bottom - toolbarHeight - 20, TRUE);
        
        return 0;
    }

    default:
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
}
